package com.luo.controller;

import com.luo.constant.MessageConstant;
import com.luo.constant.RedisConstant;
import com.luo.constant.RedisMessageConstant;
import com.luo.entity.Result;
import com.luo.util.SMSUtils;
import com.luo.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @author Zoro
 * @date 2021年08月29
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {


    @Autowired
    private JedisPool jedisPool;


    /**
     * 发送订单验证码
     */
    @RequestMapping("/send4Order.do")
    public Result validateCode(String telephone) {
        try {
            //生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //发送验证码
            SMSUtils.sendShortMessage(telephone, code.toString());
            //存入到redis中
            jedisPool.getResource().setex(RedisMessageConstant.SENDTYPE_ORDER + telephone, 60 * 60 * 24, code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 发送登录验证码
     */
    @RequestMapping("/send4Login.do")
    public Result loginValidateCode(String telephone) {
        try {
            //2. 生成动态验证码(4或者6位)
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //3. 使用阿里云发送短信验证码
            SMSUtils.sendShortMessage(telephone, code.toString());
            //4. 把验证码存到redis(存5分钟)
            jedisPool.getResource().setex(RedisMessageConstant.SENDTYPE_LOGIN + telephone, 5 * 60, code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }


}
